package com.dc.base.view.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.annotation.StyleRes
import androidx.appcompat.app.AppCompatDialogFragment
import androidx.fragment.app.DialogFragment
import com.dc.base.R

class CommonDialogFragment private constructor() : AppCompatDialogFragment() {

    private var mLayoutId = 0
    private var mCancelable = false
    private var mStyle = R.style.FullScreenDialogStyle
    var convertView: ((holder: DialogViewHolder, dialog: CommonDialogFragment) -> Unit)? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(DialogFragment.STYLE_NO_TITLE, mStyle)
    }

    override fun onStart() {
        super.onStart()
        isCancelable = mCancelable
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(mLayoutId, container, false).apply {
            convertView?.let {
                it(DialogViewHolder.createView(this), this@CommonDialogFragment)
            }
        }
    }

    companion object {

        fun newInstance(@LayoutRes layoutResId: Int) : CommonDialogFragment {
            return CommonDialogFragment().apply {
                this.mLayoutId = layoutResId
            }
        }


        // -------------------------------单例1-------------------------------------
        @Volatile
        private var instance: CommonDialogFragment? = null

        fun getInstance(@LayoutRes layoutResId: Int) =
            instance ?: synchronized(this) {
                instance ?: CommonDialogFragment().also {
                    instance = it
                    it.mLayoutId = layoutResId
                }
            }

        // -------------------------------单例2--------------------------------
        val instance2: CommonDialogFragment by lazy { CommonDialogFragment() }
    }

    fun setDialogStyle(@StyleRes style: Int = R.style.FullScreenDialogStyle) {
        mStyle = style
    }

    fun setDialogCancelable(cancelable: Boolean = false) {
        mCancelable = cancelable
    }
}